import React from 'react';
import { useLocation } from 'react-router-dom';

// 检查权限的函数
const checkPermission = (permission, routeName) => {
  const localStorageRoutes = JSON.parse(localStorage.getItem("routes")) || [];
  const currentRoute = localStorageRoutes.find(
    (item) => item.routeName === routeName
  );
  return (
    currentRoute?.buttons.some((button) => button.action === permission) ||
    false
  );
};

// 自定义钩子
const useHasPermission = (permission) => {
  const location = useLocation();
  const routeName = location.pathname;
  const hasPermission = checkPermission(permission, routeName);

  if (!hasPermission) {
    console.error("没有权限");
    return null;
  }

  return { hasPermission };
};

// 示例组件
const MyComponent = (props) => {
  const { hasPermission } = useHasPermission("some_permission");
  if (!hasPermission) return null;

  return (
    <div>
      <h1>这是一个受权限保护的组件</h1>
      {/* 组件内容 */}
    </div>
  );
};

export default MyComponent;